package com.ciwong.epaper.modules.epaper.adapter;

import android.content.Context;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.me.ui.LoadingFileActivity;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.util.download.ProgressCircle;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 书箱目录列表adapter Created by res-jianpingliu on 2015/7/24.
 */
public class CatalogAdapter extends BaseAdapter {
    private List<DownLoadInfo> mList;

    private boolean isHideDownloadBtn = false;// 是否隐藏下载按钮

    private LayoutInflater mInflater;

    private int LIST_TYPE;

    private Context mContext;

    private Handler mHandler = new Handler();

    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    public CatalogAdapter(Context context, List<DownLoadInfo> directionList,
                          boolean isHideDownloadBtn, int type) {
        mInflater = LayoutInflater.from(context);
        if (directionList == null) {
            directionList = new ArrayList<DownLoadInfo>();
        }
        mList = directionList;
        this.isHideDownloadBtn = isHideDownloadBtn;
        this.LIST_TYPE = type;
        mContext = context;
    }

    @Override
    public int getCount() {
        if (mList != null && !mList.isEmpty()) {
            return mList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (mList != null && !mList.isEmpty()) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.adapter_directory_item,
                    null);
            holder = new ViewHolder();
            holder.titleTv = (TextView) convertView
                    .findViewById(R.id.directory_item_title_tv);
            holder.progressCircle = (ProgressCircle) convertView
                    .findViewById(R.id.directory_item_min_pb);
            holder.horPb = (ProgressBar) convertView.findViewById(R.id.directory_item_hor_pb);

            holder.sizeTv = (TextView) convertView.findViewById(R.id.size_tv);
            holder.speedTv = (TextView) convertView.findViewById(R.id.down_speed__tv);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
            // item.horPb.setProgress(0);
        }

        DownLoadInfo info = null;
        try {
            info = mList.get(position);
        } catch (Exception e) {
            e.printStackTrace();
            notifyDataSetChanged();
            return convertView;
        }

        holder.titleTv.setText(info.getChapterName());

        holder.sizeTv.setText(info.getSize() + " MB");

        dealCircleProgress(info, holder.horPb, holder.progressCircle, holder.speedTv);
        if (isHideDownloadBtn) {
            convertView.setBackgroundColor(Color.WHITE);
        }
        return convertView;
    }


    private void dealCircleProgress(final DownLoadInfo info,
                                    final ProgressBar horPb,
                                    final ProgressCircle progressCircle,
                                    //final TextView sizeText,
                                    final TextView speedText) {
        if (isHideDownloadBtn || (LIST_TYPE == CatalogueInfo.LIST_COMPLETED
                && info.getStatus() == DownloadStatus.STATUS_COMPLETED)) {
            progressCircle.setVisibility(View.GONE);
            speedText.setVisibility(View.GONE);
            return;
        }
        progressCircle.setIsError(false);
        Log.i("lqi","---LoadingFileActivity Item  info Status: ---"+info.getStatus());
        switch (info.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
            case DownloadStatus.STATUS_PENDING:
                horPb.setProgress(0);
                progressCircle.updateDownloadProgress(0);
                progressCircle.setIsError(TextUtils.isEmpty(info.getUrl()));
                progressCircle.initToNormal();
                break;
            case DownloadStatus.STATUS_LOADING:
                horPb.setProgress(0);
                progressCircle.initToLoading();
                break;

            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoadInfo currentInfo = DownLoad.getInstance()
                        .getCurrentBean(info);
                if (currentInfo != null) {
                    info.setProgress(currentInfo.getProgress());
                }
                //实时下载的网速
                long downSpeed = getNetSpeed();
                speedText.setText(downSpeed / 1024 + " kb/s");
                horPb.setProgress(info.getProgress());
                progressCircle
                        .updateDownloadProgress(info.getProgress() / 100f);
                break;

            case DownloadStatus.STATUS_COMPLETED:
                if (LIST_TYPE == CatalogueInfo.LIST_ALL) {
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_ALL" + packageDir);
                    if (new File(packageDir).exists()) {
                        horPb.setProgress(0);
                        progressCircle.initToCompleted();
                    } else {
                        info.setProgress(0);
//                        DownLoad.getInstance().stopTask(info);
                    }
                    speedText.setVisibility(View.GONE);
                } else if (LIST_TYPE == CatalogueInfo.LIST_DOWNLOADING) {
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_DOWNLOADING" + packageDir);
                    if (new File(packageDir).exists()) {
                        mList.remove(info);
                        if (mContext instanceof LoadingFileActivity) {
                            ((LoadingFileActivity) mContext).showLlEmpty();
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                notifyDataSetChanged();
                            }
                        }, 10);
                    } else {
                        DownLoad.getInstance().pauseTask(info);
                    }
                    speedText.setVisibility(View.GONE);
                    horPb.setVisibility(View.GONE);
                }
                break;
            case DownloadStatus.STATUS_PAUSE:
                horPb.setProgress(info.getProgress());
                progressCircle.initToPause();
                break;
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
                horPb.setProgress(0);
                Log.i("se7en", this.getClass().getName()
                        + "DownloadStatus.STATU_FAILED");
                progressCircle.initToFAILED();
                break;
            case DownloadStatus.STATUS_UPZIPING:
                horPb.setProgress(100);
                progressCircle.initToLoading();
                break;
        }
    }

    private class ViewHolder {
        TextView titleTv, sizeTv, speedTv;

        ProgressBar horPb;

        ProgressCircle progressCircle;
    }

    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return traffic_data;
    }

}
